<template>
  <div>
    <h2>我的课表</h2>
    <table>
      <thead>
        <tr>
          <th>时间/日期</th>
          <th v-for="day in days" :key="day">{{ day }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(time, index) in times" :key="index">
          <th>{{ time }}节</th>
          <td v-for="day in days" :key="day">
            <div v-for="appointment in getFilteredAppointments(day, time)" :key="appointment.id">
              <span>{{ appointment.courseName }}</span>
              <span> - {{ appointment.labName }}</span>
              <span v-if="appointment.weekRange">({{ appointment.weekRange }})</span>
            </div>
            <div v-if="getFilteredAppointments(day, time).length === 0">无课</div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'MySchedule',
  data() {
    return {
      appointments: [], // 存储从后端获取的预约信息
      days: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      times: ['1、2', '3、4', '5、6', '7、8', '9、10', '11、12']
    };
  },
  created() {
    this.fetchAppointments();
  },
  methods: {
    async fetchAppointments() {
      try {
        const teacherId = localStorage.getItem('username'); // 从localStorage获取登录账号名作为教师ID
        const token = localStorage.getItem('token');
        const response = await axios.get(`http://192.168.129.76:8080/api/appointment_json/${teacherId}`,    {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        if (response.data.code === 200) {
          this.appointments = response.data.data;
          this.mergeAppointments();
        } else {
          console.error('获取课表信息失败，响应码：', response.data.code);
          alert('获取课表信息失败，请检查网络连接。');
        }
      } catch (error) {
        console.error('获取课表信息错误:', error);
        if (error.response && error.response.status !== 200) {
          alert('Token无效或已过期，请重新登录。');
        } else {
          alert('获取课表信息失败，请检查网络连接。');
        }
      }
    },
    mergeAppointments() {
      const mergedMap = new Map();
      this.appointments.forEach(appointment => {
        const key = `${appointment.courseName}-${appointment.labName}-${appointment.section}`;
        if (!mergedMap.has(key)) {
          mergedMap.set(key, {
            ...appointment,
            weekRange: `${appointment.week}`,
            weeks: [appointment.week]
          });
        } else {
          const existing = mergedMap.get(key);
          const weeks = [...existing.weeks, appointment.week].sort((a, b) => a - b);
          const startWeek = weeks[0];
          const endWeek = weeks[weeks.length - 1];
          mergedMap.set(key, {
            ...existing,
            weeks,
            weekRange: `${startWeek}-${endWeek}`
          });
        }
      });
      this.appointments = Array.from(mergedMap.values());
    },
    getFilteredAppointments(day, time) {
      return this.appointments.filter(a =>
        a.dayofweek === this.days.indexOf(day) + 1 &&
        a.section === this.sectionToTimeIndex(time)
      );
    },
    sectionToTimeIndex(timeStr) {
      const timeIndexMap = {
        '1、2': 1, '3、4': 2, '5、6': 3, '7、8': 4, '9、10': 5, '11、12': 6
      };
      return timeIndexMap[timeStr];
    }
  }
};
</script>

<style scoped>
table {
  width: 100%;
  max-width: 1200px;
  border-collapse: collapse;
  margin: 20px auto; /* 使表格居中并添加外边距 */
  font-family: Arial, sans-serif; /* 设置表格字体 */
}
th, td {
  border: 1px solid #cfe0ff;
  padding: 15px 30px;
  text-align: left;
}
thead {
  background-color: #d8e3f5; /* 设置表头背景颜色为蓝色 */
  color: rgb(127, 139, 192); /* 设置表头文本颜色为白色 */
}
td{
  background-color: #f3f7ff;
}
th {
  position: sticky; /* 使表头在滚动时固定 */
  top: 0; /* 表头固定在顶部 */
  z-index: 1; /* 确保表头在滚动时保持在最上层 */
}
hr {
  margin: 4px 0;
  border: 0;
  height: 1px;
  background-color: #eee;
}
.jie{
  background-color: #d8e3f5;
  color: rgb(127, 139, 192); 
}
</style>